package com.happyelements.components
{
	import com.happyelements.display.HEStage;
	import com.happyelements.isolib.IsoTileAnimation;
	import com.happyelements.isolib.IsoUtil;
	import com.happyelements.isolib.IsoWorld;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.geom.Point;
	
	public class MapScene extends Sprite
	{
		private const BITMAP_PADDING:Number = 100;
		
		private var _world:IsoWorld;
		
		private var _heStage:HEStage;
		
		private var _canvas:BitmapData;
		
		public function MapScene()
		{
			initWorld();
			
			initBitmapLayer();
		}
		
		public function addTileObject(tile:IsoTileAnimation):void
		{
			IsoWorld.instance.addTileObject(tile);
		}
		
		public function update():void
		{
			IsoWorld.instance.update();
		}
		
		public function hasTileObject(tile:IsoTileAnimation):Boolean
		{
			return (_world.tileObjectWarehouse.indexOf(tile) != -1);
		}
		
		public function removeTileObject(tile:IsoTileAnimation):void
		{
			_world.removeTileObject(tile);
		}
		
		public function convertPointToColRow(x:Number, y:Number):Point
		{
			var result:Point = new Point(x, y);
			result = _world.globalToLocal(result);
			result = IsoUtil.sceneToRowColumn(result.x, result.y);
			
			return result;
		}
		
		private function initWorld():void
		{
			_world = IsoWorld.instance;
			_world.initWorld(20, 32);
			
			addChild(_world);

			IsoWorld.bitmapOffset = new Point(BITMAP_PADDING + _world.width / 2, BITMAP_PADDING);
		}
		
		private function initBitmapLayer():void
		{
			_heStage = new HEStage(_world.width, _world.height + BITMAP_PADDING);
			_canvas = new BitmapData(_heStage.stageWidth, _heStage.stageHeight, true, 0x000000FF);

			var bitmap:Bitmap = new Bitmap(_canvas);
			
			bitmap.x = -BITMAP_PADDING - _world.width / 2;
			bitmap.y = -BITMAP_PADDING;
			addChild(bitmap);
			
			addEventListener(Event.ENTER_FRAME, tickLogic);
			addEventListener(Event.RENDER, tickRender);
		}
		
		private function tickLogic(event:Event):void
		{
			stage.invalidate();
		}
		
		private function tickRender(event:Event):void
		{
			_canvas.lock();
			
			_canvas.fillRect(_canvas.rect, 0x00000000);
			
			updateChildren();
			
			_heStage.update(this._canvas, _heStage.getRect());
			
			_canvas.unlock();
		}
		
		private function updateChildren():void
		{
			while (_heStage.numChildren)
			{
				_heStage.removeChildAt(0);
			}
			
			//Set children depth here
			for (var i:int = IsoWorld.instance.tileObjectWarehouse.length - 1; i >= 0; i--)
			{
				var child:IsoTileAnimation = IsoWorld.instance.tileObjectWarehouse[i] as IsoTileAnimation;
				_heStage.addChildAt(child.getTypedDisplayObject(), 0);
			}
		}
	}
}